var autoconfigSettings = null;

Pebble.addEventListener("ready", function(e) {
  {% if 'items' in preferences %}
  try {
    autoconfigSettings = JSON.parse(localStorage['{{shortName}}']);
    MessageQueue.sendAppMessage(autoconfigSettings);
  }
  catch(e) {
    // the dicitonary was never stored, the watchapp uses its default values
    autoconfigSettings = {};
    localStorage['{{shortName}}'] = JSON.stringify(autoconfigSettings);
  }
  {% endif %}
  if(typeof autoconfigReady == 'function'){
    autoconfigReady();
  }
});

{% if 'embedded' in preferences and preferences['embedded'] == true -%}
{% macro embed() %}{% include "autoconfig.html.jinja" %}{% endmacro %}
var config_html={{ embed()|embed_html  }}

{% endif -%}

Pebble.addEventListener("showConfiguration", function (e) {
  if(typeof autoconfigShowConfiguration == 'function'){
    autoconfigShowConfiguration();
  }
  {% if 'embedded' in preferences and preferences['embedded'] == true -%}
  var html = config_html.replace("REPLACED_AT_RUNTIME", localStorage['{{shortName}}']);
  Pebble.openURL('data:text/html,' + encodeURIComponent(html + '<!--.html'));
  {%- else -%}
  var url = "{{ preferences['url'] }}?";

  for (var key in autoconfigSettings) {
    if (autoconfigSettings.hasOwnProperty(key)) {
      url += encodeURIComponent(key) + "=" + encodeURIComponent(autoconfigSettings[key]) + "&";
    }
  }

  console.log("Hosted URL: " + url);

  Pebble.openURL(url);
  {%- endif %}
});

Pebble.addEventListener("webviewclosed", function(e) {
  {% if 'items' in preferences %}
    if ((typeof e.response === 'string') && (e.response.length > 0)) {
        var newSettings = decodeURIComponent(e.response);
        autoconfigSettings = JSON.parse(newSettings);

        localStorage['{{shortName}}'] = newSettings;
        MessageQueue.sendAppMessage(autoconfigSettings);
    }
  {% endif %}

  if(typeof autoconfigWebviewclosed == 'function'){
    autoconfigWebviewclosed();
  }
});

var MessageQueue=function(){var RETRY_MAX=5;var queue=[];var sending=false;var timer=null;return{reset:reset,sendAppMessage:sendAppMessage,size:size};function reset(){queue=[];sending=false}function sendAppMessage(message,ack,nack){if(!isValidMessage(message)){return false}queue.push({message:message,ack:ack||null,nack:nack||null,attempts:0});setTimeout(function(){sendNextMessage()},1);return true}function size(){return queue.length}function isValidMessage(message){if(message!==Object(message)){return false}var keys=Object.keys(message);if(!keys.length){return false}for(var k=0;k<keys.length;k+=1){var validKey=/^[0-9a-zA-Z-_]*$/.test(keys[k]);if(!validKey){return false}var value=message[keys[k]];if(!validValue(value)){return false}}return true;function validValue(value){switch(typeof value){case"string":return true;case"number":return true;case"object":if(toString.call(value)=="[object Array]"){return true}}return false}}function sendNextMessage(){if(sending){return}var message=queue.shift();if(!message){return}message.attempts+=1;sending=true;Pebble.sendAppMessage(message.message,ack,nack);timer=setTimeout(function(){timeout()},1e3);function ack(){clearTimeout(timer);setTimeout(function(){sending=false;sendNextMessage()},200);if(message.ack){message.ack.apply(null,arguments)}}function nack(){clearTimeout(timer);if(message.attempts<RETRY_MAX){queue.unshift(message);setTimeout(function(){sending=false;sendNextMessage()},200*message.attempts)}else{if(message.nack){message.nack.apply(null,arguments)}}}function timeout(){setTimeout(function(){sending=false;sendNextMessage()},1e3);if(message.ack){message.ack.apply(null,arguments)}}}}();